package com.example.study_manger.service;

import com.example.study_manger.entity.ApplyPermission;
import com.example.study_manger.entity.Organization;
import com.example.study_manger.entity.Role;
import com.example.study_manger.entity.UserTb;
import com.example.study_manger.repository.ApplyPermissionRe;
import com.example.study_manger.repository.RoleRe;
import com.example.study_manger.repository.UserTbRe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private RoleRe roleRe;
    @Autowired
    private ApplyPermissionRe applyPermissionRe;
    public UserTb login(UserTb userTb){
        return userTbRe.findByUsernameAndPassword(userTb.getUsername(), userTb.getPassword());
    }
    //TODO:完善注册
    public ApplyPermission register(ApplyPermission applyPermission){
        try{
            return applyPermissionRe.save(applyPermission);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }
    public Boolean getUsername(String username) {
        return userTbRe.existsByUsername(username);
    }

    public UserTb getUserInfo(String userName) {
        return userTbRe.findByUsername(userName);
    }

    public Page<UserTb> getUserByRole(List<Role> allByRoleName, int page, int size) {
        return userTbRe.findAllByRoleIn(allByRoleName, PageRequest.of(page-1, size));
    }

    public Page<UserTb> findAll(PageRequest of) {
        return userTbRe.findAll(of);
    }

    public Page<UserTb> getUserByOrgId(Long organizationId, int page, int size) {
        Organization organization = new Organization();
        organization.setId(organizationId);
        List<Role> roles = roleRe.findByOrganization(organization);
        return userTbRe.findAllByRoleIn(roles, PageRequest.of(page-1, size));
    }
}
